package com.wyg.blog.config;

import com.wyg.blog.filter.*;
import com.wyg.blog.service.serviceimpl.MyUserDetailsServiceImpl;
import com.wyg.blog.service.user.UserService;
import com.wyg.blog.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.CorsUtils;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

/**
 * @description:
 * @author: WYG
 * @time: 2020/6/22 22:09
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    MyUserDetailsServiceImpl myUserDetailsService;
    @Autowired
    UserService userService;

    @Autowired
    MyAuthenticationEntryPoint myAuthenticationEntryPoint;

    @Autowired
    MyAccessDeniedHandler myAccessDeniedHandler;

    @Autowired
    MyLogoutHandler myLogoutHandler;

    @Autowired
    MyLogoutSuccessHandler myLogoutSuccessHandler;

    @Autowired
    RsaKeyProperties rsaKeyProperties;

    @Autowired
    RedisUtil redisUtil;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/api/upload/picture","/api/view/message/getMyMessages",
                "/api/view/message/publishMessage","/api/view/blog/getAllBlogs","/api/view/blog/getBlogsByTypeId",
                "/api/view/blog/getBlogsByTagId","/api/view/type/getAllTypes","/api/view/type/getLatestTags",
                "/api/view/type/getAllTags","/api/view/type/getLatestTypes","/api/view/blog/getLatestBlog",
                "/api/view/blog/getArchiveBlog","/api/IpAddress/getIpAddress","/api/view/blog/getBlogById",
                "/api/view/comment/publishComment","/api/view/comment/getComments","/api/view/blog/updateViews",
                "/api/view/blog/updateLikes","/api/view/type/getCounts","/api/view/type/getPartTags",
                "/api/view/type/getPartTypes","/api/search/searchBlog","/api/view/authorInfo/getInfo","/api/view/site/getAllSite",
                "/api/view/authorInfo/getContent");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //解决跨域问题。cors 预检请求放行,让Spring security 放行所有preflight request（cors 预检请求）
        http.authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll();
        //让Security永远不会创建HttpSession，它不会使用HttpSession来获取SecurityContext
        http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().headers().cacheControl();
        http.authorizeRequests()
                .antMatchers("/api/user/register").permitAll();
        http.addFilterAt(new MyUsernamePasswordAuthenticationFilter(super.authenticationManager(),userService,rsaKeyProperties,redisUtil), UsernamePasswordAuthenticationFilter.class);
        http.addFilterBefore(new MyOncePerRequestFilter(rsaKeyProperties,myUserDetailsService), UsernamePasswordAuthenticationFilter.class);
        http.exceptionHandling().authenticationEntryPoint(myAuthenticationEntryPoint).accessDeniedHandler(myAccessDeniedHandler);
        http.logout().addLogoutHandler(myLogoutHandler).logoutSuccessHandler(myLogoutSuccessHandler);
        http.cors(Customizer.withDefaults());
    }
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOrigin("*");//修改为添加而不是设置，* 最好改为实际的需要，我这是非生产配置，所以粗暴了一点
        configuration.addAllowedMethod("*");//修改为添加而不是设置
        configuration.addAllowedHeader("*");//这里很重要，起码需要允许 Access-Control-Allow-Origin
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
